package com.dongrj.framework.starter.sms.client;

import com.dongrj.framework.core.utils.JsonUtils;
import com.dongrj.framework.starter.sms.*;
import com.dongrj.framework.starter.sms.enums.SmsEnum;
import com.dongrj.framework.starter.sms.properties.WeiDaoYunSmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.util.Assert;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Slf4j
public class WeiDaoYunSmsClient extends AbstractSmsClient {
    private static final String URL = "http://api.wddz.xyz:8001/sms/api/sendMessageMass";

    private final WebClient webClient;

    private final WeiDaoYunSmsProperties weiDaoYunSmsProperties;

    public WeiDaoYunSmsClient(WebClient webClient, WeiDaoYunSmsProperties weiDaoYunSmsProperties) {
        this.webClient = webClient;
        this.weiDaoYunSmsProperties = weiDaoYunSmsProperties;
    }

    @Override
    public void sendBefore(SmsRequest smsRequest) {
        Assert.notNull(smsRequest.getContent(), "发送消息内容不能为空!");
    }

    @Override
    public SmsResponse doSend(SmsRequest smsRequest) {
        WeiDaoSendParam weiDaoSendParam = toWeiDaoSendParam(smsRequest);
        Mono<String> post = WebClientUtils.post(log, this.webClient, URL, weiDaoSendParam);
        String block = post.block();
        WeiDaoSendResponse response = JsonUtils.toBean(block, WeiDaoSendResponse.class);
        SmsResponse smsResponse = SmsResponse.fail();
        if (Objects.equals(response.getCode(), 0)) {
            smsResponse.setCode(1);
            return smsResponse;
        }
        log.info("doSend.response={}", response);
        smsResponse.setMessage(response.getMessage());
        return smsResponse;
    }

    private WeiDaoSendParam toWeiDaoSendParam(SmsRequest smsRequest) {
        WeiDaoSendParam weiDaoSendParam = new WeiDaoSendParam();
        weiDaoSendParam.setUserName(this.weiDaoYunSmsProperties.getUserName());
        weiDaoSendParam.setContent(smsRequest.getContent());
        weiDaoSendParam.setPhoneList(mobileToList(smsRequest.getMobiles()));
        long timestamp = System.currentTimeMillis();
        weiDaoSendParam.setTimestamp(timestamp);
        weiDaoSendParam.setSign(calcSignCode(timestamp));
        return weiDaoSendParam;
    }

    public String calcSignCode(long timestamp) {
        String md5Password = DigestUtils.md5Hex(this.weiDaoYunSmsProperties.password);
        String signCode = DigestUtils.md5Hex(this.weiDaoYunSmsProperties.userName + timestamp + md5Password);
        log.info("calcSignCode.signCode={}", signCode);
        return signCode;
    }

    @Override
    public SmsEnum smsEnum() {
        return SmsEnum.WeiDaoYun;
    }
}
